<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use app\common\trait\SettingsTrait;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\validate\MassageUser as ValidateMassageUser;
use plugin\ycMassage\utils\enum\State;
use support\Request;

class UserController extends BaseController
{
    use SettingsTrait;

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('uid', 'input', 'UID', [
            'placeholder' => 'UID搜索'
        ]);
        $builder->addScreen('mobile', 'input', '手机号', [
            'placeholder' => '手机号搜索'
        ]);
        $builder->addTopButton('add', '创建用户', [
            'api'       => $this->pluginPrefix . '/admin/User/create',
            'path' => '/User/create',
            'type'      => 'modal'
        ], [
            'title' => '创建用户',
        ], [
            'type' => 'success'
        ]);
        $builder->addRightButton('edit', '修改', [
            'api'    => $this->pluginPrefix . '/admin/User/update',
            'path' => '/User/update',
            'type'      => 'modal'
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('money', '代客充值', [
            'api'    => $this->pluginPrefix . '/admin/UserWallet/money',
            'path' => '/UserWallet/money',
            'type'      => 'modal'
        ], [], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->addRightButton('log', '明细', [
            'api'    => $this->pluginPrefix . '/admin/UserWallet/log',
            'path' => '/UserWallet/log',
            'aliasParams' => [
                'id' => 'uid'
            ]
        ], [], [
            'type' => 'info',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('mobile', '手机号', [
                'width' => 120,
            ])
            ->addColumn('nickname', '昵称',[
                'minWidth' => 120,
            ])
            ->addColumn('pnickname', '上级', [
                'width' => 120,
            ])
            ->addColumn('dealer_nickname', '分销', [
                'width' => 120,
            ])
            ->addColumn('age', '年龄', [
                'width' => 120,
            ])
            ->addColumn('birthday', '生日', [
                'width' => 120,
            ])
            ->addColumn('gender_text', '性别', [
                'width' => 120,
            ])
            ->addColumn('realname', '真实姓名', [
                'width' => 120,
            ])
            ->addColumn('idcard', '身份证号', [
                'width' => 160,
            ])
            ->addColumnEle('is_realname', '实名', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => [
                        0=>'未实名',
                        1=>'已实名'
                    ],
                    'style' => [
                        0=>[
                            'type'=>'info'
                        ],
                        1=>[
                            'type'=>'success'
                        ]
                    ]
                ],
            ])
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'switch',
                    'api' => $this->pluginPrefix . '/admin/User/updateState',
                    'checked' => [
                        'text' => '可用',
                        'value' => 1
                    ],
                    'unchecked' => [
                        'text' => '不可用',
                        'value' => 0
                    ]
                ],
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['u.saas_appid', '=', $request->saas_appid]
        ];
        $uid = $request->get('uid');
        if (!empty($uid)) {
            $where[] = ['u.id', '=', $uid];
        }
        $mobile = $request->get('mobile');
        if (!empty($mobile)) {
            $where[] = ['u.mobile', 'like', '%' . $mobile . '%'];
        }
        $data = MassageUser::where($where)
            ->alias('u')
            ->join('massage_user p', 'u.puid=p.id', 'left')
            ->join('massage_user d', 'u.dealer_uid=d.id', 'left')
            ->order('id desc')
            ->field('u.*,p.nickname as pnickname,d.nickname as dealer_nickname')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                $item->is_realname=0;
                if($item->realname){
                    $item->is_realname=1;
                }
                if($item->puid){
                    $item->pnickname = "({$item->puid})".base64_decode($item->pnickname);
                }
                if($item->dealer_uid){
                    $item->dealer_nickname = "({$item->dealer_uid})".base64_decode($item->dealer_nickname);
                }
            });
        return $this->successRes($data);
    }
    public function create(Request $request)
    {
        if ($request->method() === 'POST') {
            $D = $request->post();
            hpValidate(ValidateMassageUser::class, $D, 'create');
            $MassageUser = new MassageUser();
            $D['saas_appid'] = $request->saas_appid;
            if (!empty($D['headimg'][0])) {
                $D['headimg'] = UploadService::path($D['headimg'][0]);
            }
            if (empty($D['password'])) {
                $D['password'] = substr($D['mobile'], -6);
            }
            if ($MassageUser->save($D)) {
                return $this->success('添加成功');
            }
            return $this->fail('添加失败');
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('mobile', 'input', '手机号', '', [
            'col' => 12,
        ]);
        $builder->addRow('password', 'input', '密码', '', [
            'col' => 12,
            'props' => [
                'placeholder' => '不填写则默认为手机号后六位'
            ]
        ]);
        $builder->addRow('nickname', 'input', '昵称', '', [
            'col' => 12,
        ]);
        $builder->addComponent('headimg', 'uploadify', '头像', '', [
            'col' => 12,
            'props' => [
                'type' => 'image',
                'limit' => 1,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $builder->addRow('state', 'radio', '状态', 1, [
            'col' => 12,
            'options' => State::getOptions()
        ]);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function update(Request $request)
    {
        $id = $request->get('id');
        $MassageUser = MassageUser::where('id', $id)->withoutField('password')->find();
        if ($request->method() === 'POST') {
            $D = $request->post();
            hpValidate(ValidateMassageUser::class, $D, 'update');
            if (!empty($D['headimg'][0])) {
                # 判断url中是否包含thirdwx.qlogo.cn
                if (!strpos($D['headimg'][0], 'thirdwx.qlogo.cn')) {
                    $D['headimg'] = UploadService::path($D['headimg'][0]);
                }
            }
            if ($MassageUser->save($D)) {
                return $this->success('添加成功');
            }
            return $this->fail('添加失败');
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('mobile', 'input', '手机号', '', [
            'col' => 12,
        ]);
        $builder->addRow('password', 'input', '密码', '', [
            'col' => 12,
            'props' => [
                'placeholder' => '不填写则不修改密码'
            ]
        ]);
        $builder->addRow('nickname', 'input', '昵称', '', [
            'col' => 12,
        ]);
        $builder->addComponent('headimg', 'uploadify', '头像', '', [
            'col' => 12,
            'props' => [
                'type' => 'image',
                'limit' => 1,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $builder->addRow('state', 'radio', '状态', 1, [
            'col' => 12,
            'options' => State::getOptions()
        ]);
        $data = $builder->setData($MassageUser)->create();
        return $this->successRes($data);
    }
    public function updateState(Request $request)
    {
        $id = $request->post('id');
        $MassageUser = MassageUser::where(['id' => $id, 'saas_appid' => $request->saas_appid])->find();
        $MassageUser->state = $MassageUser->state ? 0 : 1;
        if ($MassageUser->save()) {
            return $this->success('修改成功');
        }
        return $this->fail('修改失败');
    }
}
